package com.itheima.tanhua.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.common.ResultInfo;
import com.itheima.domain.db.Admin;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//每次请求登录状态校验
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    //仅仅是在进入controller之前进行拦截判断
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1. 查看session中是否有我们指定的用户对象
        Admin admin = (Admin) request.getSession().getAttribute("SESSION_ADMIN");

        if (admin != null) {
            //2. 代表session存在,也就是用户处于登录状态,放行请求即可
            return true;
        } else {
            //3. 代表session不存在,
            // 3-1 告诉前端页面,当前用户未登录
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
            String json = new ObjectMapper().writeValueAsString(resultInfo);
            response.getWriter().write(json);

            // 3-2禁止通行
            return false;
        }
    }
}